<template>
    <Dialog v-model="dialogVisible" :title="dialogTitle" width="600">
        <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="110px">
            <el-form-item label="琴房类型名称" prop="name">
                <el-input v-model="formData.name" clearable placeholder="请输入琴房类型名称"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </template>
    </Dialog>
</template>
<script lang="ts" setup>
import {useRoomTypeApi} from "@/api/yxt/room";
import {useMessage} from "@/components/Notice";

defineOptions({name: 'YxtRoomTypeForm'})

const {t} = useI18n()
const roomTypeApi = useRoomTypeApi();

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
    id: undefined,
    name: '',
})
const formRules = reactive({
    name: [{required: true, message: '房间类型名称不能为空', trigger: ['blur', 'change']}],
})
const formRef = ref()

const open = async (type: string, id?: number) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    if (id) {
        formLoading.value = true
        try {
            formData.value = await roomTypeApi.getRoomType(id)
        } finally {
            formLoading.value = false
        }
    }
}
defineExpose({open})

const emit = defineEmits(['success'])
const submitForm = async () => {
    formRef.value?.validate(async (valid: any) => {
        if (valid) {
            formLoading.value = true
            try {
                const data = formData.value
                if (formType.value === 'create') {
                    await roomTypeApi.createRoomType(data);
                    useMessage(t('common.createSuccess'))
                } else {
                    await roomTypeApi.updateRoomType(data);
                    useMessage(t('common.updateSuccess'))
                }
                dialogVisible.value = false
                emit('success')
            } finally {
                formLoading.value = false
            }
        }
    });
}

const resetForm = () => {
    formData.value = {
        id: undefined,
        name: '',
    }
    formRef.value?.resetFields()
}
</script>
